import mongoose, { Document, Schema } from 'mongoose';

export interface ILog extends Document {
    timestamp: Date,
    userId: mongoose.Schema.Types.ObjectId,
    username: string,
    action: string,          // 如 "update"
    description: string,     // 自然语言描述
    ip: string,
    resourceId?: mongoose.Schema.Types.ObjectId
}
const logSchema = new Schema<ILog>({
    timestamp: {
        type: Date,
        default: Date.now
    },
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        required: [true, '用户ID是必填项'],
    },
    username: {
        type: String,
        required: [true, '用户名是必填项'],
        trim: true,
        minlength: [2, '用户名至少需要2个字符'],
        maxlength: [50, '用户名不能超过50个字符']
    },
    action: {
        type: String,
        required: [true, '操作是必填项'],
        trim: true,
    },
    description: {
        type: String,
        required: [true, '描述是必填项'],
        trim: true,
    },
    ip: {
        type: String,
        required: [true, 'IP地址是必填项'],
        trim: true,
    },
    resourceId: {
        type: mongoose.Schema.Types.ObjectId,
    }
}, {
    timestamps: true // 自动添加 createdAt 和 updatedAt
});

// 创建索引
logSchema.index({ createdAt: -1 });

// 虚拟字段（不存储在数据库中）
logSchema.virtual('displayName').get(function () {
    return `${this.username} (${this.action})`;
});

// 实例方法
logSchema.methods.toJSON = function () {
    const log = this.toObject();
    return log;
};

// 静态方法
logSchema.statics.findByUserId = function (userId: mongoose.Schema.Types.ObjectId) {
    return this.find({ userId });
};

export const Log = mongoose.model<ILog>('Log', logSchema);
